package com.ffapp.rainmonitorcustom.gis;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.ffapp.rainmonitorcustom.R;
import com.ffapp.rainmonitorcustom.basis.BasisApp;
import com.ffapp.rainmonitorcustom.basis.BasisFragment;
import com.ffapp.rainmonitorcustom.basis.Constants;
import com.ffapp.rainmonitorcustom.bean.DeviceListBeanTwo;
import com.ffapp.rainmonitorcustom.bean.DeviceListData;
import com.ffapp.rainmonitorcustom.event.MessageEvent;
import com.ffapp.rainmonitorcustom.map.MarkerListData;
import com.ffapp.rainmonitorcustom.util.MyUtils;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import my.http.HttpRestClient;
import my.http.MyHttpListener;

/***
 * 地图
 * **/
public class MapFragment extends BasisFragment implements AMapLocationListener, LocationSource {


    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.tv_sw)
    TextView tvSw;
    @BindView(R.id.tv_ph)
    TextView tvPh;
    @BindView(R.id.tv_yd)
    TextView tvYd;
    @BindView(R.id.tv_ry)
    TextView tvRy;
    @BindView(R.id.icon_img)
    ImageView mMapIcon;
    @BindView(R.id.ll_info)
    LinearLayout llInfo;

    public static MapFragment newInstance() {
        MapFragment fragment = new MapFragment();
        return fragment;
    }

    private AMap aMap;
    private MapView mapView;

    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    DeviceListBeanTwo mDeviceListBean;
    DeviceListData mDeviceListData;

    private String keyword = "";


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser == true){
            llInfo.setVisibility(View.GONE);
        }
        if (clickedMarker != null) {
            clickedMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_icon_location_grey));
            clickedMarker = null;
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.gis_map_fragment);
        mapView = (MapView) findViewById(R.id.map);
        clickedMarker = null;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
        init();
//        mlocationClient.startLocation();
        getList();

    }

    private void getList() {
        RequestParams params = new RequestParams();
//        showProgress();
        params.put("keyword", keyword);
        HttpRestClient.get(Constants.URL_MAP_LIST, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        mDeviceListBean = (DeviceListBeanTwo) result;
                        setViews();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, DeviceListBeanTwo.class);

    }

    void setViews() {
//        ArrayList<MarkerListData> mListBean = new ArrayList<>();
//        MarkerListData data;
        // 设置所有maker显示在当前可视区域地图中
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        DeviceListData DeviceListData;
        for (int i = 0, l = mDeviceListBean.getList().size(); i < l; i++) {
            DeviceListData = mDeviceListBean.getList().get(i);
            MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                    .fromResource(DeviceListData.getMapMarkerResid()))
                    .position(DeviceListData.getLatlng())
                    .title(DeviceListData.getStnm())
                    .snippet(DeviceListData.getStlc());
            Marker marker = aMap.addMarker(markerOption);
            marker.setObject(DeviceListData);
            builder.include(DeviceListData.getLatlng());
//            marker.showInfoWindow();
        }


        LatLngBounds bounds = builder.build();
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 15));

//        data = new BaseListData(f)
    }

//    private void getList() {
//
//        ArrayList<MarkerListData> mListBean = new ArrayList<>();
//        MarkerListData data;
//        data = new MarkerListData(new LatLng(39.761, 116.434),"标题1","描述1");
//        mListBean.add(data);
//        data = new MarkerListData(new LatLng(39.161, 116.134),"标题2","描述2");
//        mListBean.add(data);
//        data = new MarkerListData(new LatLng(39.261, 116.234),"标题3","描述3");
//        mListBean.add(data);
//        data = new MarkerListData(new LatLng(39.361, 116.334),"标题4","描述4");
//        mListBean.add(data);
//        data = new MarkerListData(new LatLng(39.461, 116.434),"标题5","描述5");
//        mListBean.add(data);
//        data = new MarkerListData(new LatLng(39.561, 116.534),"标题6","描述6");
//        mListBean.add(data);
//        for (int i = 0,l = mListBean.size(); i < l ; i++){
//            data = mListBean.get(i);
//            MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
//                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
//                    .position(data.getLatlng())
//                    .title(data.getTitle())
//                    .snippet(data.getDes());
//            Marker marker = aMap.addMarker(markerOption);
//            marker.setObject(data);
//            marker.showInfoWindow();
//        }
//
//        // 设置所有maker显示在当前可视区域地图中
//        LatLngBounds bounds = new LatLngBounds.Builder()
//                .include(mListBean.get(0).getLatlng()).include(mListBean.get(mListBean.size()-1).getLatlng()).build();
//        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
//
////        data = new BaseListData(f)
//    }


    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

    }

    private void setUpMap() {
//        aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
//        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
//            @Override
//            public void onMapLoaded() {
//
//            }
//        });// 设置amap加载成功事件监听器
//        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
//            @Override
//            public boolean onMarkerClick(Marker marker) {
//                return false;
//            }
//        });// 设置点击marker事件监听器

        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.map_icon_location));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
//        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

//        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
//            /**
//             * 监听自定义infowindow窗口的infocontents事件回调
//             */
//            @Override
//            public View getInfoContents(Marker marker) {
//                return null;
//            }
//
//            /**
//             * 监听自定义infowindow窗口的infowindow事件回调
//             */
//            @Override
//            public View getInfoWindow(Marker marker) {
//                View infoWindow = getLayoutInflater().inflate(
//                        R.layout.map_custom_info_window, null);
//
//                render(marker, infoWindow);
//                return infoWindow;
//            }
//
//        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                mDeviceListData = (DeviceListData) marker.getObject();
//                new GisPopDetail(mContext, mDeviceListData).show();
                resetMarker(marker);
                llInfo.setVisibility(View.VISIBLE);
                tvDeviceName.setText("" + mDeviceListData.getStnm());
                tvSw.setText("水位：" + isEmpty(mDeviceListData.getZ()) + "/米");
                tvPh.setText("PH值：" + isEmpty(mDeviceListData.getPh())  + "/PH");
                tvYd.setText("盐度：" + "0/g");
                tvRy.setText("溶氧：" + isEmpty(mDeviceListData.getDoxy()) + "/g");
//                BasisApp.loadImg(mContext, Constants.URL_TEST_API + mDeviceListBean.getImgMap().get(mDeviceListData.getStcd()), mMapIcon, R.drawable.video_img_bg_default);
                BasisApp.loadImg(mContext, MyUtils.getServiceAPI() + mDeviceListBean.getImgMap().get(mDeviceListData.getStcd()), mMapIcon, R.drawable.video_img_bg_default);
                return true;
            }
        });
//        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
//            @Override
//            public void onInfoWindowClick(Marker marker) {
//                MarkerListData listData = (MarkerListData) marker.getObject();
//                showToast("infowendow点击了"+listData.getTitle());
//            }
//        });

//        if (mlocationClient == null) {
//            mlocationClient = new AMapLocationClient(this);
//            mLocationOption = new AMapLocationClientOption();
//            //设置定位监听
//            mlocationClient.setLocationListener(this);
//            //设置为高精度定位模式
//            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            //设置定位参数
//            mlocationClient.setLocationOption(mLocationOption);
//            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
//            // 在定位结束后，在合适的生命周期调用onDestroy()方法
//            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
////            mlocationClient.startLocation();
//        }
    }

    private String  isEmpty(String data){
        if (TextUtils.isEmpty(data)){
            return "0";
        }else {
            return data;
        }
    }

    private Marker clickedMarker = null;
    private void resetMarker(Marker marker) {
        if (clickedMarker != null) {
            clickedMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_icon_location_grey));
        }
        clickedMarker = marker;
        marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_icon_location_blue));
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        ImageView imageView = (ImageView) view.findViewById(R.id.badge);
        imageView.setImageResource(R.drawable.icon_like);
        String title = marker.getTitle();

        MarkerListData listData = (MarkerListData) marker.getObject();

        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        titleUi.setText(listData.getTitle());
        TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
        snippetUi.setText(listData.getDes());
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();

        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(mContext);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchBtnOnClick(MessageEvent messageEvent) {
        keyword = messageEvent.getMessage();
        getList();
    }

}
